package com.hpf.gupao.pattern.singleton.container;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @datetime: 2021/5/18 14:22
 * @author: huangpengfei
 */
public class ContainerSingleton {

    private static Map<String, Object> IOC = new ConcurrentHashMap<>();

    private ContainerSingleton() {

    }

    public static Object getInstance(String className) {
        if (!IOC.containsKey(className)) {
            // 根据Spring IOC容器来加锁存储单例的容器
            synchronized (IOC) {
                Object instance = null;
                try {
                    instance = Class.forName(className).newInstance();
                    IOC.put(className, instance);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                return instance;
            }
        } else {
            return IOC.get(className);
        }
    }
}
